package engine.systems.control.platformerKeyControl
{
	import engine.classes.enumerations.SystemPriority;
	import engine.systems.motion.motion.Motion;
	import engine.systems.spatial.spatial.Spatial;
	import engine.systems.update.GameSystem;
	import engine.utils.Key;
	
	public class PlatformerKeyControlSystem extends GameSystem
	{
		public function PlatformerKeyControlSystem()
		{
			super(PlatformerKeyControlNode, updateNode);
			
			this.priority = SystemPriority.UPDATE;
		}
		
		private function updateNode(node:PlatformerKeyControlNode, time:Number):void
		{
			if(node.control.locked) return;
			
			var control:PlatformerKeyControl 	= node.control;
			var motion:Motion 				= node.motion;
			var spatial:Spatial 			= node.spatial;
			
			control.falling = motion.velocityY >= 50 ? true : false;
			if(control.jumping && control.falling) control.jumping = false;
			
			if(!control.jumping && !control.falling && Key.isDown(control.jump))
			{
				control.jumping 	= true;
				motion.velocityY 	= -control.jumpVelocity;
			}
			
			var left:Boolean 	= Key.isDown(control.left);
			var right:Boolean 	= Key.isDown(control.right);
			
			if(left == right)
			{
				motion.accelerationX 	= 0;
				control._walkingLeft 	= false;
				control._walkingRight 	= false;
			}
			else if(left)
			{
				if(spatial.scaleX > 0) spatial.scaleX *= -1;
				
				motion.accelerationX 	= -control.walkAcceleration;
				control._walkingLeft 	= true;
			}
			else if(right)
			{
				if(spatial.scaleX < 0) spatial.scaleX *= -1;
				
				motion.accelerationX 	= control.walkAcceleration;
				control._walkingRight 	= true;
			}
		}
	}
}